package net.alan.modules.service.impl;

import net.alan.modules.bean.*;
import net.alan.modules.repository.FavoriteCatalogRepository;
import net.alan.modules.repository.FavoriteRepository;
import net.alan.modules.service.IFavoriteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/21
 */
@Service
public class FavoriteServiceImpl extends BaseServiceImpl implements IFavoriteService {
    private static final Logger logger = LoggerFactory.getLogger(FavoriteServiceImpl.class);
    @Autowired
    private FavoriteRepository favoriteRepository;
    @Autowired
    private FavoriteCatalogRepository favoriteCatalogRepository;

    @Override
    public JpaRepository getJpaRepository(Class<?> cla) {
        if (isSame(cla, FavoriteCatalog.class)) return favoriteCatalogRepository;
        return favoriteRepository;
    }


    @Override
    public Page<Favorite> findByUserId(Integer userId, PageModel pageModel) {
        return favoriteRepository.findByUserId(userId, pageModel.getPageable(Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Favorite> findByCatalogId(Integer catalogId, PageModel pageModel) {
        return favoriteRepository.findByCatalogId(catalogId,pageModel.getPageable(Sort.Direction.DESC, "id"));
    }

    @Override
    public List<Favorite> findByUserId(Integer userId) {
        return this.favoriteRepository.findByUserId(userId);
    }

    @Override
    public List<FavoriteCatalog> findCatalogByUserId(Integer userId) {
        return this.favoriteCatalogRepository.findByUserId(userId);
    }

    @Override
    public Result deleteCatalog(Integer id) {
        int count = this.favoriteRepository.countByCatalogId(id);
        if (count > 0) return ResultUtil.error("该目录下有收藏，不能删除");
        this.favoriteCatalogRepository.delete(id);
        return ResultUtil.success();
    }
}
